<template>
  <div ref="dom" class="charts chart-graph" style="border: 2px solid #F9FBFD;background: #F9FBFD"></div>
</template>

<script>
  import echarts from 'echarts'
  import tdTheme from './theme.json'
  import {on, off} from '@/libs/tools'

  echarts.registerTheme('tdTheme', tdTheme)
  export default {
    name: 'ChartGraph',
    props: {
      dataArr: Array,
      linkArr: Array,
      text: String,
    },
    data() {
      return {
        dom: null,
        colorArr: [
          "#E46CBB",
          "#2d8cf0",
          "#19be6b",
          "#ff9900",
          "#9A66E4",
          "#ed3f14",
          "#4D8DEF",
          "#FC8686",
          "#FFAF7F",
          "#CF97FA",
          "#62C87F",
          "#47CFC4",
          "#fac671",
          "#7171FC",
          "#EFD671"
        ],
        defChartOpnion: {
          //          backgroundColor:'#ffaa00',//背景色
          title: {
            text: ''
          },
          focusNodeAdjacency: true,
          tooltip: {},
          animationDurationUpdate: 1500,
          animationEasingUpdate: 'quinticInOut',
          series: [
            {
              force: {
                repulsion: 100,//节点之间的斥力因子。支持数组表达斥力范围，值越大斥力越大。
                gravity: 0.03,//节点受到的向中心的引力因子。该值越大节点越往中心点靠拢。
                edgeLength: 220,//边的两个节点之间的距离，这个距离也会受 repulsion。[10, 50] 。值越小则长度越长
                layoutAnimation: true
              },
              type: 'graph',
              layout: 'force',
              symbolSize: 60,
              roam: true,
              focusNodeAdjacency: true,
              edgeSymbol: ['circle', 'arrow'],
              edgeSymbolSize: [4, 10],
              edgeLabel: {},
              data: [], //数据
              links: [], //链接
              lineStyle: {
                normal: { //设置连接线的样式
                  opacity: 0.9,
                  width: 1,
                  curveness: 0,
                  color: '#a4a5a5 '
                }
              },
              itemStyle: {
                color: '#fac671', //这个参数就是修改节点的背景色的，在官网中有效，但是在这边背景色永远为白色，只更改了文本，怀疑版本问题
                shadowBlur: 0,
                borderWidth: 2,
                //                borderColor:'#333333' //这个参数有效
              },
              label: { //节点文字的样式
                show: true,
                textShadowBlur: false,
                fontSize: 12,
                fontWeight: 'lighter',
                color: "#333333"
              }
            }
          ]
        }
      }
    },
    methods: {
      resize() {
        this.dom.resize()
      },
      getLinkStyle(linkObj) {
        var defStyle = {
          label: {
            normal: {
              show: true,
              formatter: this.graphFormatter, //p.dta此处为link中的数据属性
              textStyle: {
                fontSize: 12
              }
            }
          }
        }
        for (let key in linkObj) {
          defStyle[key] = linkObj[key]
        }
        return defStyle
      },
      graphFormatter(p) {
        if (p.data.type == 'node') {
          return p.data.name;
        } else { //此处还应显示连接线独有的属性
          return p.data.linkName;
        }
      },
      graphTooltopFormatter(p) {
        var str = ""
        for (let key in p.data) {
          if (key == "_labels" || key == "itemStyle" || key == "node") {
            continue;
          }
          var content = p.data[key] + ""
          if (content.length > 30) {
            content = content.substring(0, 30) + "..."
          }
          str = str + key + ":" + content + "<br/>"
        }
        return str
      },
      genOpinion() {
//        itemStyle: {
//          color: '#fac671'
//        }
        var tmpDataArr = []

        var colorMap = {}
        var colorCount = 0
        this.dataArr.forEach(item => {
          var obj = this.copyObj(item)
          const label = obj['_labelsStr']
          if (label in colorMap) {
            const index = colorMap[label]
            obj.itemStyle = {
              color: this.colorArr[index]
            }
          } else {//新的颜色
            if (colorCount >= this.colorArr.length - 1) {
              colorCount = 0
            }
            obj.itemStyle = {
              color: this.colorArr[colorCount]
            }
            colorMap[label] = colorCount
            colorCount++
          }
          tmpDataArr.push(obj)
        });
        var option = this.defChartOpnion
        option.title.text = this.text
        option.series[0].data = tmpDataArr
        //设置tooltip  节点跟属性显示的不一致
        option.tooltip.formatter = this.graphTooltopFormatter
        var newLinkArr = []
        for (var i = 0; i < this.linkArr.length; i++) {
          var obj = this.linkArr[i];
          obj = this.getLinkStyle(obj);
          newLinkArr.push(obj)
        }
        option.series[0].links = newLinkArr
        console.log("最终option：" + JSON.stringify(option))
        return option
      },
      copyObj(obj) {
        var ret = {};
        for (let key in obj) {
          ret[key] = obj[key]
        }
        return ret
      }

    },
    mounted() {
      this.$nextTick(() => {
        this.dom = echarts.init(this.$refs.dom, 'tdTheme')
        const option = this.genOpinion()
        this.dom.setOption(option)
        on(window, 'resize', this.resize)
      })
    },
    watch: {
      //观察option的变化
      dataArr: {
        handler(newVal, oldVal) {
          if (this.dom) {
            this.dom.hideLoading();
            this.dom.clear();
            const option = this.genOpinion()
            this.dom.setOption(option);
          } else {
            this.dom = echarts.init(this.$refs.dom, 'tdTheme')
            const option = this.genOpinion()
            this.dom.setOption(option)
            on(window, 'resize', this.resize)
          }
        },
        deep: true //对象内部属性的监听，关键。
      }
    },
    beforeDestroy() {
      off(window, 'resize', this.resize)
    }
  }
</script>
